import logging, sys, traceback, tempfile, shutil, os, zipfile, pathlib

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from protolib import get_app_root
from protolib.gui_utils.pyqt5_messageboxes import show_critical_messagebox

from windows.main import MainWindow
from windows.crash_handler import CrashHandlerWindow

from config import dump_config

logger = logging.getLogger(__name__)

def excepthook(exc_type, exc_value, exc_traceback):
    error_msg = traceback.format_exception(exc_type, exc_value, exc_traceback)
    error_msg = ''.join(error_msg)
    print(error_msg)
    QApplication.closeAllWindows()
    window = CrashHandlerWindow(error_msg)
    window.show()

    # https://stackoverflow.com/questions/19462112/pyqt-wait-until-widget-closes
    loop = QEventLoop()
    window.exiting.connect(loop.quit)
    window.destroyed.connect(loop.quit)
    loop.exec() # wait ...

    sys.exit(1)

sys.excepthook = excepthook

logger.info('Graphical crash handler installed')

def main(args):
    app = QApplication(sys.argv)
    window = MainWindow(args)
    window.show()
    exit_code = app.exec()
    dump_config(window.get_tab())
    sys.exit(exit_code)